package re56.layer;

import java.util.List;
import java.util.Random;

import re56.equipment.Equipment;
import re56.packet.PDCCHPacket;
import re56.packet.Packet;

public class MACLayer
{
	private Equipment Device;
	
	private byte[] MACAddress;
	
	private Random rand = new Random();
	
	
	public MACLayer(Equipment Device)
	{
		this.Device = Device;
		
		// randomly generate a MAC Address
		MACAddress = new byte[6];
		rand.nextBytes(MACAddress);
	}
	
	
	public void sendPacket(Packet packet, Equipment e)
	{
		// add the MAC header.
		packet.getHeader().setSource(MACAddress);
		packet.getHeader().setDestination(e.getMacLayer().getMACAddress());
		
		Device.getPhysicalLayer().send(packet);
	}
	
	
	public void receivePacket(Packet packet)
	{
		// check if this packet is for me.
		if(packet.getHeader().getDestination().equals(MACAddress))
		{
			if(packet instanceof PDCCHPacket)
			{
				// we don't need to puch this packet to the Device.
				// only extract the allocated RB and save them.
				
				PDCCHPacket p = (PDCCHPacket) packet;
				
				List<Integer> RBs_UL = p.getRBs_UL();
				List<Integer> RBs_DL = p.getRBs_DL();
				
				System.out.println((RBs_UL.size()+RBs_DL.size())+" RB allocated to "+getStringMACAddress()+" : UL"+RBs_UL+" DL"+RBs_DL);
				
				// Once we received this, we can consider us as "connected"
			}
			
			Device.receive(packet);
		}
	}
	
	
	public byte[] getMACAddress()
	{
		return MACAddress;
	}
	
	
	public String getStringMACAddress()
	{
		return String.format("%02X:%02X:%02X:%02X:%02X:%02X", MACAddress[0], MACAddress[1], MACAddress[2], MACAddress[3], MACAddress[4], MACAddress[5]);
	}
	
	
	public Equipment getDevice()
	{
		return Device;
	}
}
